<?php

namespace app\common\model\merchant;

use app\common\model\BaseModel;
use think\Exception;
use yiqiniu\extend\facade\Db;

/**
 * 商户管理部门
 * Class MerchantDepartment
 * @package app\common\model\merchant
 */
class MerchantDepartmentModel extends BaseModel
{
    //
    protected $name = 'merchant_department';

    // 设置字段信息
    protected $schema = [
        'id' => 'int',        //
        'mer_id' => 'string',        // 所属商户
        'code' => 'string',        // 部门编码
        'title' => 'string',        // 部门名称
        'pid' => 'int',        // 父级部门
        'tree_path' => 'string',        // 部门路径
        'depth' => 'int',        // 部门层级
        'child' => 'int',        // 子部门数
        'sort' => 'int',        // 排序
        'is_sys' => 'int',        // 是否系统创建  1 系统创建 0商户创建
        'op_user' => 'int',        // 操作人
        'create_at' => 'datetime',        // 创建时间
        'update_at' => 'datetime',        // 更新时间
    ];

    /**
     * 创建默认的角色
     * @param array $param 创建默认部门
     * @param string $merId 商户ID
     * @return int 角色ID
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function createDefaultDept(array $param, string $merId): int
    {
        $depCode = $this->getNewCode($this->name, 'code', $merId, 3);
        $defaultData = [
            'mer_id' => $merId,
            'code' => $depCode,
            'title' => '管理员',
            'is_sys' => 1,
            'op_user' => $param['op_user'],
            'create_at' => $param['create_at']
        ];
        return $this->db('merchant_department')->insertGetId($defaultData);
    }

    /**
     * 获取子部门所有ID
     * @param $mer_id
     * @param $pid
     * @return array
     * @throws Exception
     */
    public function childIds($mer_id, $pid): array
    {
        if (empty($pid)) {
            throw new Exception("父级ID不能为空", API_ERROR);
        }
        $path = $this->where("id", $pid)->where('mer_id', $mer_id)->value(null, "tree_path");
        if (empty($path)) {
            $path = $pid;
        } else {
            $path .= "," . $pid;
        }

        $data = $this->db()->removeOption()->where('mer_id', $mer_id)
            ->whereRaw("concat(',',tree_path,',') like '," . $path . ",%'")
            ->column('id');

        $data[] = $pid;
        return $data;
    }

    /**
     * 删除部门
     * @param int $id 部门ID
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \yiqiniu\extend\exception\ApiException
     */
    public function deptDel($id, $mer_id): void
    {
        $info = $this->db()->where('id', $id)->where('mer_id', $mer_id)->field('child,pid,is_sys')->find();
        if (empty($info)) {
            api_exception(API_ERROR, '部门不存在或已删除，请刷新后重试');
        }
        if ($info['is_sys'] == 1) {
            api_exception(API_ERROR, '系统部门暂不支持删除');
        }
        if ($info['child'] > 0) {
            api_exception(API_ERROR, '请先选择删除子部门');
        }
        $this->db()->where('id', $id)->where('mer_id', $mer_id)->delete();
        if ($info['pid'] > 0) {
            $this->updateParentIDNum($info['pid'], false);
        }
    }

    /**
     * 更新父ID的节点数量
     * @param $id
     * @param $flag  true: 加1  false 减1
     * @return int
     * @throws \think\db\exception\DbException
     */
    private function updateParentIDNum($id, bool $flag = true): int
    {
        $update = ['child' => Db::raw('child' . ($flag ? '+' : '-') . '1')];
        return $this->db()->removeOption()->where('id', $id)->where('child', '>', 0)->update($update);
    }

    /**
     * 新增或修改
     * @param $params
     * @return int|string|void
     * @throws Exception
     */
    public function addEdit($params)
    {
        return $this->treeAddEdit($params);
    }
}
